
<template>
  <div class="home-page">
    <div class="task-list">
      <div class="task-list-head">
        <div class="task-title">任务管理</div>
        <div class="task-btn" @click="addTask">新增任务</div>
      </div>
      <el-table
        :data="list"
        style="width: 100%"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column prop="name" label="任务名称" width="280" align="center">
        </el-table-column>
        <el-table-column
          prop="Magnification"
          label="放大倍率"
          align="center"
        ></el-table-column>
          <el-table-column
          prop="unit_of_measurement"
          label="单位"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="description"
          label="描述"
          align="center"
        ></el-table-column>
        <el-table-column prop="status" label="状态" align="center"
          ><template>已完成</template></el-table-column
        >
        <el-table-column label="操作">
          <template #default="scope">
            <div class="edit-btns">
              <div @click="detail(scope.row)" class="edit-btn">
                <svg-icon icon-class="detail" />
              </div>
              <div @click="summary(scope.row)" class="edit-btn">
                <svg-icon icon-class="summary" />
              </div>
              <div @click="edit(scope.row)" class="edit-btn">
                <svg-icon icon-class="edit" />
              </div>
              <div @click="del(scope.row)" class="edit-btn">
                <svg-icon icon-class="delete" />
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- <pagination
        :total="pageTotal"
        :page.sync="query.page"
        :limit.sync="query.size"
        @pagination="getList"
      /> -->
    </div>

    <el-dialog
      :title="taskDialogType == 'create' ? '新增任务' : '修改任务'"
      :visible.sync="taskDialogOpen"
      width="80%"
      top="5vh"
      append-to-body
      class="scrollbar"
    >
      <div>
        <el-form
          :model="taskForm"
          :rules="taskRules"
          ref="loginForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="taskForm.name" placeholder="请输入任务名称" />
          </el-form-item>
          <el-form-item label="电镜图像" v-if="taskDialogType === 'create'">
            <el-upload
              list-type="picture-card"
              :auto-upload="false"
              action="#"
              class="upload-demo"
              :file-list="fileList"
              ref="upload"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="放大倍率" prop="Magnification">
            <el-input v-model="taskForm.Magnification" placeholder="请输入放大倍率" />
          </el-form-item>
          <el-form-item label="单位" prop="unit_of_measurement">
            <el-input
              v-model="taskForm.unit_of_measurement"
              placeholder="请输入单位（默认值: nm）"
            />
          </el-form-item>
          <el-form-item label="任务描述" prop="description">
            <el-input
              type="textarea"
              v-model="taskForm.description"
              placeholder="请输入任务描述"
              :rows="2"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="isLoading"
              type="primary"
              @click="taskDialogType === 'create' ? createTask() : editTask()"
              >提交</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
 
<script>
import { createTasks, getTasks, editTasks, delTasks } from "@/api/index";
 
import { deepClone,getQueryString } from "@/utils";
import Cookies from "js-cookie";
import Pagination from "@/components/Pagination";

var validateMagnitude = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入放大倍率"));
  } else if (
    !(
      /(^[1-9]\d*(\.\d{1,})?)$/.test(value) ||
      /(^[0](\.\d{1,}){1})$/.test(value)
    )
  ) {
    callback(new Error("请输入正数"));
  } else {
    callback();
  }
};
export default {
  name: "index",
  data() {
    return {
      isLoading: false,
      fileList: [],
      list: [],
      query: {
        page: 1,
        size: 10,
      },
      pageTotal: 0,
      taskDialogTitle: "新增任务",
      taskDialogType: "create",
      taskDialogOpen: false,
      taskForm: {
        id: "",
        name: "",
        description: "",
        Magnification: "",
        unit_of_measurement: "nm",
      },
      taskRules: {
        name: [
          {
            required: true,
            message: "请输入任务名称",
            trigger: "blur",
          },
        ],
        Magnification: [
          { required: true, massage: "请输入放大倍率", trigger: "blur" },
          { validator: validateMagnitude, trigger: "blur" },
        ],
        tasktype: [{ required: true, massage: "请选择类型", trigger: "blur" }],
      },
      dialogImageUrl: "",
      dialogVisible: false,
      duringUpload: false,
      user_id: "",
    };
  },
  components: { Pagination },
  watch: {},
  computed: {},
  async created() {
     let feishu_mobile = getQueryString("feishu_mobile")
    if(feishu_mobile) {
      localStorage.setItem("feishu_mobile",feishu_mobile);
    }
    let mobile = localStorage.getItem("feishu_mobile");
    if (mobile) {
      this.user_id = mobile.replace(/\+86/, "");
    }

    this.getTasks();
  },
  beforeDestroy() {},
  methods: {
    handleExceed(files, fileList) {
      //files指的是你刚上传的文件，fileList指的是你上传之前的文件数组
      this.$set(fileList[0], "raw", files[0]); //raw就是指文件
      this.$set(fileList[0], "name", files[0].name); //name就是指文件名
      this.$refs.upload.clearFiles(); //删除所有上传的文件
      this.$refs.upload.handleStart(files[0]); //handleStart()指的是手动选择文件，Element Plus 的el-upload有说明
    },

    async createTask(e) {
      const file = this.$refs.upload.uploadFiles[0];
      if (!file) {
        this.$message({ message: "请选择文件", type: "warning" });
        return;
      }
      if (this.duringUpload) {
        this.$message({ message: "正在处理中", type: "warning" });
        return;
      }
      this.duringUpload = true;
      this.isLoading = true;
      var formData = new FormData();
      formData.append("file", file.raw);

      formData.append(
        "task_json",
        JSON.stringify({
          id: "",
          name: this.taskForm.name,
          description: this.taskForm.description,
          Magnification: Number(this.taskForm.Magnification),
          unit_of_measurement: this.taskForm.unit_of_measurement || "nm",
        })
      );
      if (!this.user_id) return;
      let res = await createTasks(this.user_id, formData).catch((e) => null);
      if (res && res.task_id) {
        this.$message({ message: "提交成功", type: "success" });
        this.resetForm();
        this.taskDialogOpen = false;
        this.$refs.upload.clearFiles();
        this.getTasks();
      } else {
        this.$message({ message: "提交失败", type: "warning" });
      }
      this.isLoading = false;
      this.duringUpload = false;
    },
    async getTasks() {
      if (!this.user_id) {
        return;
      }
      let res = await getTasks(this.user_id);

      this.list = res;
    },
    addTask() {
      this.taskDialogType = "create";
      this.taskDialogOpen = true;
      this.resetForm();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleFileUpload(file) {
      this.loading = true;
    },

    detail(row) {
      this.$router.push({ path: "/detail", query: { id: row.id } });
    },
    summary(row) {
      this.$router.push({ path: "/summary", query: { id: row.id } });
    },
    async del(row) {
      if (!this.user_id) return;
      await delTasks(this.user_id, row.id);
      this.getTasks();
    },
    edit(row) {
      this.taskDialogType = "edit";
      this.taskDialogOpen = true;
      this.resetForm();
      this.taskForm.id = row.id;
      this.taskForm.name = row.name;
      this.taskForm.description = row.description;
      this.taskForm.Magnification = row.Magnification;
      this.taskForm.unit_of_measurement = row.unit_of_measurement;
    },
    async editTask() {
      if (this.duringUpload) {
        this.$message({ message: "正在处理中", type: "warning" });
        return;
      }
      this.isLoading = true;
      this.duringUpload = true;

      let data = {
        id: this.taskForm.id,
        name: this.taskForm.name,
        description: this.taskForm.description,
        Magnification: Number(this.taskForm.Magnification),
        unit_of_measurement: this.taskForm.unit_of_measurement || "nm",
      };
      if (!this.user_id) return;

      let res = await editTasks(this.user_id, this.taskForm.id, data).catch(
        (e) => null
      );
      if (res) {
        this.$message({ message: "提交成功", type: "success" });

        this.resetForm();
        this.taskDialogOpen = false;

        this.getTasks();
      } else {
        this.$message({ message: "提交失败", type: "warning" });
      }
      this.isLoading = false;
      this.duringUpload = false;
    },
    resetForm() {
      Object.keys(this.taskForm).forEach((item) => {
        if (item === "unit_of_measurement") {
          this.taskForm[item] = "nm";
        } else {
          this.taskForm[item] = "";
        }
      });
    },
  },
};
</script>
 <style src="@/assets/home.scss" scoped lang="scss"></style>